package com.studymaster.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.studymaster.dao.UserDao;
import com.studymaster.domain.User;


@Repository
public class UserDaoImpl implements UserDao{
    
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	protected RowMapper userRowMap = new RowMapper() {
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = new User();
			
			user.setStudentid(rs.getString("user"));
			user.setPassword(rs.getString("password"));
			user.setRoleid(rs.getInt("role_id"));
			user.setRolename(rs.getString("role_name"));			
			return user;
		}
	};
	
	
	@Override
	public User getUserById(String studentid) {
		// TODO Auto-generated method stub
		//String searchsql = "select * from user where student_id = '"+studentid +"' and password = '"+password+"'";
		
		String searchsql = "select * from user where user = ? ";
		try{
			return jdbcTemplate.queryForObject(searchsql, new Object[] { studentid },
					userRowMap);
		}catch (DataAccessException e) {
			// TODO: handle exception
			return null;
		}
		
	}

	@Override
	public boolean insertUser(User user) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteUserById(String studentid) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updateUser(User user) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updateUserPassword(String studentid, String password,
			String newpassword) {
		// TODO Auto-generated method stub
		String updatesql = "update user set  password=? where user=? and password = ?";
		return jdbcTemplate.update(updatesql, 
				new Object[]{newpassword,studentid,password},
				new int[] {java.sql.Types.VARCHAR,java.sql.Types.VARCHAR,
				           java.sql.Types.VARCHAR})>0;
	}

}
